from django_redis import get_redis_connection
from rest_framework import serializers

from MeiduoMall.utils import jwt_token
from oauth.models import OAuthQQUser
from oauth.utiles import OAuthQQ
from users.models import User


class OAuthQQUserSerializer(serializers.ModelSerializer):
    """
    保存QQ用户序列化器,
    """
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    access_token = serializers.CharField(label='操作凭证', write_only=True)
    token = serializers.CharField(read_only=True)
    mobile = serializers.RegexField(label="手机号", regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'id', 'username', 'token')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate(self, attrs):
        # 校验access_token并获取openid
        access_token = attrs.get('access_token')
        openid = OAuthQQ.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('无效的access_token')
        attrs['openid'] = openid

        # 校验短信验证码
        mobile = attrs.get("mobile")
        sms_code = attrs.get('sms_code')
        redis_conn = get_redis_connection('sms_code')
        real_sms_code = redis_conn.get('sms_code_%s' % mobile)
        if not real_sms_code:
            raise serializers.ValidationError("验证码已过期")
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        # 如果用户存在,检查用户密码
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = attrs.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError("密码错误")
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        openid = validated_data.get('openid')
        user = validated_data.get('user')
        mobile = validated_data.get('mobile')
        password = validated_data.get('password')

        if not user:
            # 如果用户不存在,创建用户,绑定openid(创建了OAuthQQUser数据)
            user = User.objects.create_user(username=mobile, mobile=mobile,password=password)
        else:
            if not user.check_password(password):
                raise serializers.ValidationError('此手机号已被使用,密码错误')
        # 绑定,创建OAuthQQUser对象
        OAuthQQUser.objects.create(user=user, openid=openid)
        # 签发jwt_token
        user.token = jwt_token.generate(user)

        # 向视图对象中补充user对象属性,以便在视图中使用user
        self.context['view'].user = user

        return user
